package com.rongke.web;

import com.baomidou.mybatisplus.plugins.Page;
import com.rongke.commons.JsonResp;
import com.rongke.model.Medicine;
import com.rongke.service.MedicineService;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

import jodd.util.StringUtil;

/**
 * @MedicineController
 * @药物Controller
 * @version : Ver 1.0
 */
@RestController
@RequestMapping(value = "/api/medicine")
@Transactional
public class MedicineController {
    private static final Logger LOGGER = Logger.getLogger(MedicineController.class);

    @Autowired
    private MedicineService     medicineService;

    /**
     * 根据药物类型ID获取下面所有的药物，分页
     * 
     * @param typeId
     * @return
     */
    @RequestMapping(value = "/selectByType", method = RequestMethod.GET)
    public JsonResp selectByType(Page<Medicine> page, int typeId) {
        LOGGER.debug("selectByType");

        try {
            Page<Medicine> result = medicineService.selectPageByTypeId(page, typeId);
            return JsonResp.ok(result);
        } catch (Exception e) {
            LOGGER.error("selectByType failed", e);
            return JsonResp.fa(null);
        }
    }

    /**
     * @根据id查找药物
     * @param id
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/selectOne", method = RequestMethod.GET)
    public JsonResp selectMedicine(int id) {
        LOGGER.debug("selectMedicine");

        try {
            Medicine result = medicineService.selectById(id);
            return JsonResp.ok(result);
        } catch (Exception e) {
            LOGGER.error("selectMedicine failed", e);
            return JsonResp.fa(null);
        }

    }

    @RequestMapping(value = "/searchMedicine", method = RequestMethod.GET)
    public JsonResp searchMedicine(String searchStr) {
        LOGGER.debug("searchMedicine");

        try {
            if (StringUtil.isEmpty(searchStr)) {
                return JsonResp.ok();
            }

            String[] searchKeys = searchStr.split(" ");

            List<Medicine> result = medicineService.search(searchKeys, 30);
            return JsonResp.ok(result);
        } catch (Exception e) {
            LOGGER.error("searchMedicine failed", e);
            return JsonResp.fa(null);
        }

    }
}
